package org.funtester.performance.books.chapter04.section2;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * 使用future解析异步HTTP客户端响应
 */
public class AsyncHttpClientFutureDemo {

    public static void main(String[] args) throws IOException, ExecutionException, InterruptedException {
        CloseableHttpAsyncClient httpAsyncClient = HttpAsyncClients.createDefault();// 创建异步HTTP客户端
        httpAsyncClient.start();// 启动异步HTTP客户端
        JSONObject params = new JSONObject();// 创建存放参数的JSON对象
        params.put("start", 0);// 添加参数
        params.put("pageSize", 10);// 添加参数
        HttpGet httpGet = HttpRequestTool.getHttpGet("http://localhost:8080/query", params);// 创建httpget请求对象
        Future<HttpResponse> responseFuture = httpAsyncClient.execute(httpGet, null);// 异步发送请求
        try {
            HttpResponse response = responseFuture.get();// 获取响应,阻塞等待
            HttpEntity entity = response.getEntity();// 获取响应实体
            String responseStr = EntityUtils.toString(entity);// 获取响应实体内容
            EntityUtils.consume(entity);// 关闭响应实体
            System.out.println(Thread.currentThread().getName() + "  " + responseStr);// 打印响应内容
        } catch (Exception e) {
            e.printStackTrace();
        }
        httpAsyncClient.close();// 关闭异步HTTP客户端
    }

}
